﻿namespace ChinaUnicom.Schedule
{
    using System;
    using System.Threading;

    public class SerialQuene : IScheduleQuene
    {
        Timer timer;

        ScheduleStack stack;

        ITask pendingTask;

        public SerialQuene()
        {
            stack = new ScheduleStack();
            timer = new Timer(OnTimerCallback, null, Timeout.Infinite, Timeout.Infinite);
            Status = Status.Ready;
        }

        public void Schedule(ITask task)
        {
            if (task == pendingTask)
            {
                return;
            }

            stack.Push(task);
            if (Status == Status.Ready)
            {
                Status = Status.Running;
                pendingTask = stack.Pop();
                TimerChange(task.Pending);

                if (StatusChanged != null)
                {
                    StatusChanged(this, new StatusChangedArgs(Status));
                }
            }
        }

        void OnTimerCallback(object state)
        {
            ITask task = pendingTask;
            task.Completed += OnTasksCompleted;

            try
            {
                task.Start();
            }
            catch (Exception ex)
            {
                if (task != null)
                {
                    task.Completed -= OnTasksCompleted;
                }

                // ignore the exception, just go.
                // GoForward();

                if (Error != null)
                {
                    Error(this, new ScheduleExceptionArgs(task, ex));
                }
            }
        }

        void OnTasksCompleted(object sender, EventArgs e)
        {
            ITask task = sender as ITask;
            if (task != null)
            {
                task.Completed -= OnTasksCompleted;
            }

            GoForward();
        }

        void GoForward()
        {
            if (stack.Count > 0)
            {
                pendingTask = stack.Pop();
                TimerChange(pendingTask.Pending);
            }
            else
            {
                Status = Status.Ready;

                if (StatusChanged != null)
                {
                    StatusChanged(this, new StatusChangedArgs(Status));
                }
            }
        }

        void TimerChange(int pending)
        {
            timer.Change(pending, Timeout.Infinite);
        }

        public void Dispose()
        {
            timer.Dispose();
            stack.Dispose();
            pendingTask = null;
        }

        public Status Status { get; private set; }

        public event EventHandler<ScheduleExceptionArgs> Error;

        public event EventHandler<StatusChangedArgs> StatusChanged;
    }
}
